package com.geeksaga.validator;

import java.util.Map;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.geeksaga.common.constant.SagaConstants;
import com.geeksaga.common.util.StringUtils;
import com.geeksaga.domain.Bbs;
import com.geeksaga.domain.BbsType;
import com.geeksaga.domain.User;
import com.geeksaga.service.CategoryService;
import com.geeksaga.service.BbsTypeService;

/**
 * @author newbie
 * @since 0.1
 */
public class BbsValidator implements Validator {
    private BbsTypeService bbsTypeService = null;
    private CategoryService bbsCategoryService = null;
    private String command = null;
    
    public BbsValidator() {
    }
    
    public BbsValidator(BbsTypeService bbsTypeService, CategoryService bbsCategoryService, String command) {
    	this.bbsTypeService = bbsTypeService;
    	this.bbsCategoryService = bbsCategoryService;
    	this.command = command;
    }
    
    /* (non-Javadoc)
     * @see org.springframework.validation.Validator#supports(java.lang.Class)
     */
    @SuppressWarnings("rawtypes")
	public boolean supports(Class clazz) {
        return clazz.equals(User.class);
    }
    
    /* (non-Javadoc)
     * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
     */
    public void validate(Object object, Errors errors) {
        Bbs bbs = (Bbs) object;
        
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userPasswd", "error.empty.userPasswd", "error...");

		if (!SagaConstants.REMOVE.equals(command)) {
			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title", "error.empty.title", "error...");
			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userNick", "error.empty.userNick", "error...");

			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "content", "error.empty.content", "error...");

			BbsType type = bbsTypeService.findCacheByBbsId(bbs.getBbsId());

			if (type != null) {
				Map<String, String> categoryList = bbsCategoryService.findCacheByTargetId(bbs.getBbsId());
				
				if ((categoryList != null && !categoryList.isEmpty()) && type.getCategoryYn().equals(SagaConstants.USE_YES)) {
					if (bbs.getCategorySid().equals("-1"))
						errors.rejectValue("categorySid", "error.empty.categorySid", "error...");
				}

				if (!StringUtils.isEmpty(bbs.getUserEmail()) && bbs.getUserEmail().indexOf(SagaConstants.AT) < 0)
					errors.rejectValue("userEmail", "error", "error...");
			}
		}
    }
}